function val = isbehind(P,X)
% val = ISBEHIND(P, X) Returns true if point X is behind camera P
%   Given a camera matrix is of the form: P = K*M, M = [R | -RC],
%   and a homogeneous point X of the form X = [X Y Z 1],
%   returns true if the point is behind the camera and false if not.

% Copyright (c) Michael Warren 2013

% This file is part of the AMMCC Toolbox.

% The AMMCC Toolbox is free software: you can redistribute it and/or modify
% it under the terms of the GNU Lesser General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
% 
% The AMMCC Toolbox is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU Lesser General Public License for more details.
% 
% You should have received a copy of the GNU Lesser General Public License
% along with the AMMCC Toolbox.  If not, see <http://www.gnu.org/licenses/>.

MM = P(1:3,1:3);
m = MM(3,:);
x = P*X;

det1 = det(MM);

mmag = sqrt(m(1)*m(1) + m(2)*m(2) + m(3)*m(3));
if(det1 < 0)
    out = -1*x(3)/(X(4)*mmag);
else
    out = x(3)/(X(4)*mmag);
end

% Return the corresponding boolean based on the value of out
if(out > 0)
    val = 1;
else
    val = 0;
end
return